import {
	Component,
	PureComponent,
	isValidElement,
	useState,
	useEffect,
} from 'react'
import ReactDOM from 'react-dom'
import Dialog from './Dialog.js'
let ModalContainer = null
const modelSysbol = Symbol('$$__model__Container_hidden')
class Modal extends PureComponent {
	// 渲染底部按钮
	renderFooter = () => {
		const { onOk, onCancel, cancelText, okText, footer } = this.props
		if (footer && isValidElement(footer)) return footer
		return (
			<div className="model-bottom">
				<div className="model-btn-box">
					<button
						onClick={(e) => {
							onOk?.(e)
						}}
						className="ok-btn"
					>
						{okText || '确定'}
					</button>
					<button
						onClick={(e) => {
							onCancel?.(e)
						}}
						className="cancel-btn"
					>
						{cancelText || '取消'}
					</button>
				</div>
			</div>
		)
	}
	// 渲染顶部
	renderTop = () => {
		const { title, onClose } = this.props

		return (
			<div className="model-top">
				<p>{title}</p>
				<span
					className="model-top-close"
					onClick={() => {
						onClose?.()
					}}
				>
					x
				</span>
			</div>
		)
	}
	// 渲染弹窗内容
	renderContent = () => {
		const { content, children } = this.props
		return isValidElement(content) ? content : children ? children : null
	}

	render() {
		const { visible, width = 500, closeCb, onClose } = this.props
		return (
			<Dialog
				closeCb={closeCb}
				onClose={onClose}
				visible={visible}
				width={width}
			>
				{this.renderTop()}
				{this.renderContent()}
				{this.renderFooter()}
			</Dialog>
		)
	}
}
/* 静态属性 show 控制 */
Modal.show = function (config) {
	// 如果 modal 已经存在了，那么就不需要二次 show 了
	if (ModalContainer) return
	const props = { ...config, visible: true }
	const container = (ModalContainer = document.createElement('div'))
	// const root = createRoot(container)
	/* 创建一个管理者，管理 modal 状态 */
	const manager = (container[modelSysbol] = {
		setShow: null,
		mounted: false,
		hidden() {
			const { setShow } = manager
			setShow?.(false)
		},
		destory() {
			/* 卸载组件 */
			ReactDOM.unmountComponentAtNode(container)
			// root.unmount()
			/* 移除节点 */
			document.body.removeChild(container)
			/* 质空元素 */
			ModalContainer = null
		},
	})

	const ModelApp = (props) => {
		const { visible, ...trueProps } = props
		const [show, setShow] = useState(visible)
		manager.setShow = setShow
		useEffect(() => {
			/* 卸载完成，设置状态 */
			manager.mounted = true
		}, [])

		return (
			<Modal
				{...trueProps}
				closeCb={() => {
					manager.mounted && manager.destory()
				}}
				visible={show}
			/>
		)
	}

	/* 插入到 body 中 */
	document.body.appendChild(container)
	/* 渲染 */
	// root.render(<ModelApp {...props} />)
	ReactDOM.render(<ModelApp {...props} />, container)
	return manager
}

Modal.hide = function () {
	if (!ModalContainer) return
	/* 如果存在 ModalContainer 那么隐藏 ModalContainer */
	ModalContainer[modelSysbol]?.hidden()
}

export default Modal
